package mwa.cs.rq.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.CustMonthlyDAO;
import mwa.cs.dao.CustomerDAO;
import mwa.cs.dao.DeptRateDAO;
import mwa.cs.dao.MeterBrandDAO;
import mwa.cs.dao.MeterSizeDAO;
import mwa.cs.dao.RequestDAO;
import mwa.cs.dao.RequestQuoteDAO;
import mwa.cs.dao.RouteDetailDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.database.Database;
import mwa.cs.model.CustMonthly;
import mwa.cs.model.Customer;
import mwa.cs.model.Request;
import mwa.cs.model.RouteDetail;
import mwa.cs.util.JDate;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class CS61002Srvl
 */
public class CS61002Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
	private String vaUrlAddress;
	private String vaAgentBrowser;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS61002Srvl() {
        super();
        // TODO Auto-generated constructor stub
    }

    @SuppressWarnings("unchecked")
	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		vaUrlAddress = request.getParameter("url_address");
		vaAgentBrowser = request.getParameter("agent_browser");
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		String vaProcessType = request.getParameter("methodType");
		if(vaProcessType.equals("getDropDown")){
			getDropDown(request, response);
		}else if (vaProcessType.equals("getData")){
			getData(request, response);
		} else {
			saveData(request, response);
		}
	}
	
	@SuppressWarnings("unchecked")
	public void getDropDown(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {	
		Database db = new Database();
		PrintWriter voOut = response.getWriter();
		String[] vaMessageMeterBrand = null, vaValueMeterBrand = null;
		MeterBrandDAO voMeterBrandDAO = new MeterBrandDAO(db);
		// Get value MeterBrand
		List<Map<String, Object>> voResultMeterBrand = voMeterBrandDAO.findMeterBrandBySiteId(vnSiteId);
		vaValueMeterBrand = new String[voResultMeterBrand.size()];
		vaMessageMeterBrand = new String[voResultMeterBrand.size()];
		for (int i = 0; i < voResultMeterBrand.size(); i++) {
			Map<String, Object> voObject = voResultMeterBrand.get(i);
			vaValueMeterBrand[i] = (String) voObject.get("METER_BRAND_CODE");
			vaMessageMeterBrand[i] = (String) voObject.get("METER_BRAND_DESCRIPTION");
		}
		
		JSONObject voObject = new JSONObject();
		// Check value MeterBrand
		JSONArray voListMessagesMeterBrand = new JSONArray();
		if (vaMessageMeterBrand != null) {
			for (int i = 0; i < vaMessageMeterBrand.length; i++) {
				voListMessagesMeterBrand.add(vaMessageMeterBrand[i]);
			}
		}
		JSONArray voListValuesMeterBrand = new JSONArray();
		if (vaValueMeterBrand != null) {
			for (int i = 0; i < vaValueMeterBrand.length; i++) {
				voListValuesMeterBrand.add(vaValueMeterBrand[i]);
			}
		}
		voObject.put("valuesMeterBrand", voListValuesMeterBrand);
		voObject.put("messagesMeterBrand", voListMessagesMeterBrand);
		db.close();
		voOut.print(voObject.toJSONString());
	}
    
	@SuppressWarnings("unchecked")
	public void getData(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		PrintWriter voOut = response.getWriter();
		JSONObject voObject = new JSONObject();
		Database db = new Database();
    	RequestDAO voRequestDAO = new RequestDAO(db);
    	RequestQuoteDAO voRequestQuoteDAO = new RequestQuoteDAO(db);

		String vaRequestNumber = request.getParameter("requestNumber");
		String vaAccount = "";
		String vaCustomerClass = "";
		String vaFullName = "";
		String vaMeterSize = "";
		String vaMeterSizeCode = "";
		String vaStatus = "";
		
		List<Map<String, Object>> voArrayList = null;
		Map<String, Object> voMapRequest = new HashMap<String, Object>();
		Map<String, Object> voMapRequestQuote = new HashMap<String, Object>();
		voMapRequest = voRequestDAO.getRequestForInstall(vnSiteId, vaRequestNumber);
    	if (voMapRequest == null) {
    		voObject.put("message", "resultNull");
    	} else {
    		vaStatus = ""+ voMapRequest.get("STATUS");
    		if (vaStatus.equals("1")) {
    			voArrayList = voRequestQuoteDAO.searchRequestQuoteCount(vnSiteId, vaRequestNumber);
    			if (voArrayList.size() > 0) {
    				voObject.put("message", "status1");
    			} else {
    				vaAccount = ""+ voMapRequest.get("ACCOUNT");
    				vaCustomerClass = ""+ voMapRequest.get("DESCRIPTION");
    				vaFullName = ""+ voMapRequest.get("FULL_NAME");
    				vaMeterSize = "" + voMapRequest.get("DESCRIPTION_METERSIZE");
    				vaMeterSizeCode = "" + voMapRequest.get("METER_SIZE");
			    	
			    	voObject.put("account", vaAccount);
					voObject.put("customerClass", vaCustomerClass);
					voObject.put("fullName", vaFullName);
					voObject.put("meterSize", vaMeterSize);
					voObject.put("meterSizeCode", vaMeterSizeCode);
			    	
    			}
    		} else if (vaStatus.equals("3")) {
    			voObject.put("message", "status3");
    		} else if (vaStatus.equals("4")){
    			voObject.put("message", "status4");
    		} else {
    			vaAccount = ""+ voMapRequest.get("ACCOUNT");
				vaCustomerClass = ""+ voMapRequest.get("DESCRIPTION");
				vaFullName = ""+ voMapRequest.get("FULL_NAME");
				vaMeterSize = "" + voMapRequest.get("DESCRIPTION_METERSIZE");
				vaMeterSizeCode = "" + voMapRequest.get("METER_SIZE");
		    	
		    	voObject.put("account", vaAccount);
				voObject.put("customerClass", vaCustomerClass);
				voObject.put("fullName", vaFullName);
				voObject.put("meterSize", vaMeterSize);
				voObject.put("meterSizeCode", vaMeterSizeCode);
    		}
    	}
    	db.close();
    	voOut.print(voObject.toJSONString());
	}
	
	@SuppressWarnings("unchecked")
	public void saveData(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	
    	PrintWriter out = response.getWriter();
		JSONObject voObject = new JSONObject();
		Database db = new Database();
		
		RequestDAO voRequestDAO = new RequestDAO(db);
		CustomerDAO voCustomerDAO = new CustomerDAO(db);
		DeptRateDAO voDeptRateDAO = new DeptRateDAO(db);
		RouteDetailDAO voRouteDetailDAO = new RouteDetailDAO(db);
		CustMonthlyDAO voCustMonthlyDAO = new CustMonthlyDAO(db);

		Request voRequest = new Request();
		Customer voCustomer = new Customer();
		RouteDetail voRouteDetail = new RouteDetail();
		CustMonthly voCustMonthly = new CustMonthly();
		
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());

		String vaMeterSizeCode = request.getParameter("meterSizeCode");
		String vaRequestNumber = request.getParameter("requestNumber");
		String vaMeterInstallDate = request.getParameter("meterInstallDate").trim();
		String vaMeterDate = request.getParameter("meterDate").trim();
		String vaChooseMeterBrand = request.getParameter("chooseMeterBrand").trim();
		String vaMeterSerialNumber = request.getParameter("meterSerialNumber").trim();
		String vaMeterNumber = request.getParameter("meterNumber").trim();
		
		// check value 
		String vaMaxMonthCustMonthly = voCustMonthlyDAO.findMaxMonth(vnSiteId);
		
		// set ค่า Request
		voRequest.setVaMeterBrand(vaChooseMeterBrand);
		voRequest.setVaMeterSerialNumber(vaMeterSerialNumber);
		voRequest.setVaMeterNumber(vaMeterNumber);
		voRequest.setVaMeterInstallDate(vaMeterInstallDate.substring(6, 10) + vaMeterInstallDate.substring(3, 5) + vaMeterInstallDate.substring(0, 2));
		voRequest.setVaMeterDate(vaMeterDate.substring(6, 10) + vaMeterDate.substring(3, 5) + vaMeterDate.substring(0, 2));
		voRequest.setVaStatus("3");
		voRequest.setVnUpdateUserId(1); //(Integer) request.getSession().getAttribute("user_id");
		voRequest.setVaUpdateDate(JDate.getDate());
		voRequest.setVaUpdateTime(JDate.getTime());
		voRequest.setVnSiteId(vnSiteId);
		voRequest.setVaRequestNumber(vaRequestNumber);
		
		// set ค่า Customer
		voCustomer.setVnSiteId(vnSiteId);
		voCustomer.setVaStatus("2");
		voCustomer.setVaMeterBrand(vaChooseMeterBrand);
		voCustomer.setVaMeterSerialNumber(vaMeterSerialNumber);
		voCustomer.setVaMeterNumber(vaMeterNumber);
		voCustomer.setVaMeterInstallDate(vaMeterInstallDate.substring(6, 10) + vaMeterInstallDate.substring(3, 5) + vaMeterInstallDate.substring(0, 2));
		voCustomer.setVaMeterDate(vaMeterDate.substring(6, 10) + vaMeterDate.substring(3, 5) + vaMeterDate.substring(0, 2));
		voCustomer.setVnDeptAmount(Integer.parseInt(voDeptRateDAO.findDeptAmountByMeterSize(vnSiteId, vaMeterSizeCode)));
		voCustomer.setVnInsertUserId(1); //(Integer) request.getSession().getAttribute("user_id");
		voCustomer.setVaInsertDate(JDate.getDate());
		voCustomer.setVaInsertTime(JDate.getTime());
		
		// set ค่า RouteDetail
		voRouteDetail.setVnSiteId(vnSiteId);
		voRouteDetail.setVnZoneId(0);
		voRouteDetail.setVnRouteId(0);
		voRouteDetail.setVnSeq(0);
		voRouteDetail.setVaMeterReadDate(vaMeterDate.substring(6, 10) + vaMeterDate.substring(3, 5) + vaMeterDate.substring(0, 2));
		voRouteDetail.setVnInsertUserId(1); //(Integer) request.getSession().getAttribute("user_id");
		voRouteDetail.setVaInsertDate(JDate.getDate());
		voRouteDetail.setVaInsertTime(JDate.getTime());
		
		// set ค่า CustMonthly
		voCustMonthly.setVnSiteId(vnSiteId);
		voCustMonthly.setVnZoneId(0);
		voCustMonthly.setVnRouteId(0);
		if (!vaMaxMonthCustMonthly.equals("00")) {
			voCustMonthly.setVaPeriodMonth(vaMaxMonthCustMonthly);
			voCustMonthly.setVaPeriodYear(voCustMonthlyDAO.findMaxYear(vnSiteId));
		} else {
			voCustMonthly.setVaPeriodMonth(JDate.getPreviousMonth(JDate.getMonth(), JDate.getYear()));
			voCustMonthly.setVaPeriodYear(JDate.getYearOfPreviousMonth(JDate.getMonth(), JDate.getYear()));
		}
		voCustMonthly.setVnSeq(0);
		voCustMonthly.setVaMeterNumber(vaMeterSerialNumber);
		voCustMonthly.setVaMeterReadNumber(vaMeterNumber);
		voCustMonthly.setVaReadDate(vaMeterDate.substring(6, 10) + vaMeterDate.substring(3, 5) + vaMeterDate.substring(0, 2));
		voCustMonthly.setVnConsumption(0);
		voCustMonthly.setVnAverageConsumption(0);
		voCustMonthly.setVnWaterFee(0);
		voCustMonthly.setVnWaterCharge(0);
		voCustMonthly.setVnVatAmount(0);
		voCustMonthly.setVnBillAmount(0);
		voCustMonthly.setVaStatus("2");
		voCustMonthly.setVnInsertUserId(1); //(Integer) request.getSession().getAttribute("user_id");
		voCustMonthly.setVaInsertDate(JDate.getDate());
		voCustMonthly.setvaInsertTime(JDate.getTime());
		
		try {
			db.beginTransaction();
			boolean vbResult = voRequestDAO.updateRequestForInstall(voRequest);
			if (vbResult) {
				vbResult = voCustomerDAO.SaveCustomerForInstall(voCustomer, vaRequestNumber);
				if (vbResult) {
					vbResult = voRouteDetailDAO.SaveRouteDetailForInstall(voRouteDetail, vaRequestNumber);
					if (vbResult) {
						vbResult = voCustMonthlyDAO.SaveCustMonthlyForInstall(voCustMonthly, vaRequestNumber);
						if (vbResult) {
							voObject.put("message", "success");
							db.commit();
						} else {
							voObject.put("message", "fail");
						}
					} else {
						voObject.put("message", "fail");
					}
				} else {
					voObject.put("message", "fail");
				}
			} else {
				voObject.put("message", "fail");
			}
		} catch (Exception e) {
    		SMErrorLogDAO.getInstance().addLog(0, "CS61002", JDate.getDate(), JDate.getTime(),vnUserId, "CS61002Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);	
			db.rollback();
			voObject.put("message", "fail");
		}
		db.close();
		out.print(voObject.toJSONString());
    }
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		 processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		 processRequest(request, response);
	}

}
